const dayjs = require("dayjs");
// 生成分数处理模块
exports.score = async (req, res) => {
  // 分 team_id  user_id 把分放进去
  const { id, team_id } = req.user;
  const { score } = req.query;
  const create_time = dayjs().format("YYYY-MM-DD HH:mm:ss");
  // 查询库里是否存在用户信息
  const selectUserSql = `select user_name from fa_users WHERE team_id=? AND id=?`;
  const sqlResult = await global.query(selectUserSql, [team_id, id]);
  if (sqlResult.length > 0) {
    const selectSql =
      "SELECT * FROM  fa_rank WHERE user_id =? and team_id=?";
    const result = await global.query(selectSql, [id, team_id]);
    console.log(result)
    if (result.length > 0) {
      if (result[0].score < score) {
        const update_sql = `UPDATE fa_rank SET score = ?, create_time = ? WHERE team_id=? AND user_id=?`;
        global
          .query(update_sql, [score, create_time, team_id, id])
          .then((sqlRes) => {
            if (sqlRes.affectedRows !== 1) {
              return res.cc("插入失败");
            }
            res.cc("插入" + sqlRes.affectedRows + "条成功");
          });
      } else {
        return res.cc("您的分数不需要更新!");
      }

    } else {
      const user_name = sqlResult[0]["user_name"];
      const sql = `INSERT INTO fa_rank(user_id,team_id,user_name,score,create_time) VALUES(?,?,?,?,?) `;
      global
        .query(sql, [id, team_id, user_name, score, create_time])
        .then((sqlRes) => {
          if (sqlRes.affectedRows !== 1) {
            return res.cc("插入失败");
          }
          res.cc("插入" + sqlRes.affectedRows + "条成功");
        });
    }
  } else {
    return res.cc("暂无用户信息");
  }
};
// 获取score的列表处理模块
exports.getScore = async (req, res) => {
  const { id } = req.user;
  const sql1 = `SELECT * FROM fa_rank WHERE user_id = ${id}`;
  let userInfo = {}
  let userRes = await global.query(sql1)
  if (userRes.length > 0) {
    userInfo = userRes[0]
  }
  const sql = `SELECT * FROM fa_rank order by score desc`;
  global.query(sql).then((sqlResults) => {
    if (sqlResults.length > 0) {
      sqlResults.map((it, inde) => {
        if(userInfo.user_id == it.user_id){
          userInfo.index = inde+1
        }
      })
      res.send({ code: 200, msg: "success", data: sqlResults, userInfo });
    } else {
      return res.cc("暂无分数信息");
    }
  });
};
// 获取score的列表处理模块
exports.getZScore = async (req, res) => {
  const sql = `SELECT t.team_id, t.nick_name, SUM(r.score) AS total_score  FROM fa_rank r
  JOIN fa_team t ON r.team_id = t.team_id GROUP BY t.team_id, t.nick_name ORDER BY total_score DESC;`;
  global.query(sql).then((sqlResults) => {
    
    if (sqlResults.length > 0) {
      const mylist = []
      sqlResults.map((item) => {

        if(item.team_id != 0 && item.team_id != 100){
          mylist.push(item)
        }
      })
      res.send({
        code: 200,
        msg: "success",
        data: { list: mylist },
      });
    } else {
      return res.cc("暂无团队排行信息");
    }
  });
};
